package org.ishequ.service;

import java.io.File;

import org.ishequ.net.download.DownloadProgressListener;
import org.ishequ.net.download.FileDownloader;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

/*
 * UI控件画面的重绘(更新)是由主线程负责处理的，如果在子线程中更新UI控件的值，更新后的值不会重绘到屏幕上
 * 一定要在主线程里更新UI控件的值，这样才能在屏幕上显示出来，不能在子线程中更新UI控件的值
 */
public class DownloadTask implements Runnable{
	private String path;
	private File saveDir;
	private FileDownloader loader;
	private Handler handler;
	private Context context;
	private ProgressBar progressBar;
	
	public DownloadTask(String path, File saveDir, Handler handler, Context context ,ProgressBar progressBar) {
		this.path = path;
		this.saveDir = saveDir;
		this.handler = handler;
		this.context = context;
		this.progressBar = progressBar;
	}
	/**
	 * 退出下载
	 */
	public void exit(){
		if(loader!=null) loader.exit();
	}
	
	public void run() {
		try {
			loader = new FileDownloader(this.context, path, saveDir, 3);
			progressBar.setMax(loader.getFileSize());//设置进度条的最大刻度
			loader.download(new DownloadProgressListener() {
				public void onDownloadSize(int size) {
					Message msg = new Message();
					msg.what = 1;
					msg.getData().putInt("size", size);
					handler.sendMessage(msg);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
			handler.sendMessage(handler.obtainMessage(-1));
		}
	}			
}
